package de.slothsoft.bookmaker.parse.impl;

import static de.slothsoft.bookmaker.parse.impl.MangaEdenDescription.REGEX_URL;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.xpath.XPathException;

import de.slothsoft.bookmaker.parse.ImageXPathParser;
import de.slothsoft.bookmaker.parse.OverviewParser;
import de.slothsoft.bookmaker.parse.ParseContext;
import de.slothsoft.bookmaker.parse.WebsiteDescription;
import de.slothsoft.bookmaker.parse.WebsiteParser;
import de.slothsoft.bookmaker.parse.XPathUtil;
import de.slothsoft.bookmaker.parse.OverviewParser.ParserCreator;

public class MangaEdenOverviewDescription implements WebsiteDescription {

    public static final String REGEX_PAGE = ".*[0-9.]+/[0-9.]+(/){0,1}$";

    @Override
    public String getDisplayName() {
        return "mangaeden.com (Overview)";
    }

    @Override
    public boolean isSupported(String url) {
        return url.matches(REGEX_URL) && !url.matches(REGEX_PAGE);
    }

    @Override
    public WebsiteParser createParser(ParseContext context, InputStream input) throws IOException {
        try {
            TagNode tagNode = new HtmlCleaner().clean(input);
            Document document = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
            List<String> urls = XPathUtil.findAttributes(document, "//a[@class='chapterLink']", "href");
            cleanUpPageUrls(urls);
            return createOverviewParser(urls);
        } catch (XPathException | ParserConfigurationException | XPathExpressionException e) {
            throw new IOException(e);
        }
    }

    private static void cleanUpPageUrls(List<String> pageUrls) {
        int length = pageUrls.size();
        for (int i = 0; i < length; i++) {
            pageUrls.set(i, "http://www.mangaeden.com" + pageUrls.get(i));
        }
    }

    protected static OverviewParser createOverviewParser(List<String> chapterUrls) {
        return new OverviewParser(new ParserCreator() {

            @Override
            public ImageXPathParser createParser(InputStream input, String chapterUrl) throws IOException {
                return MangaEdenDescription.createParser(input, chapterUrl);
            }
        }, chapterUrls);
    }
}
